var express = require('express');
var router = express.Router();
let { personnelModel } = require('../db/wen')
let { areaModel } = require('../db/tian')

router.get('/personnel', async (req, res, err) => {
  let query = req.query
  console.log(query);
  let reg = RegExp(query.name, 'ig')
  let con = await personnelModel.aggregate([
    {
      $lookup: {
        from: 'area',
        localField: 'region',
        foreignField: '_id',
        as: "region",
      }
    },
    {
      $match: {
        name: reg
      }
    }
  ])
  // let con = await personnelModel.find({ name: reg }).skip((query.page - 1) * 10).limit(10)
  res.send({
    code: 200,
    message: '获取人员列表信息',
    data: con
  })
})
router.post('/personnel', async (req, res) => {
  console.log(req.body, '添加');
  personnelModel.create(req.body)
  res.send({
    code: 200,
    message: '添加成功！'
  })
})
router.put('/personnel', async (req, res) => {
  console.log(req.body, '修改');
  await personnelModel.findOne({ _id: req.body._id }).updateOne(req.body)
  res.send({
    code: 200,
    message: '修改成功！'
  })
})
router.delete('/personnel', async (req, res) => {
  console.log(req.body);
  await personnelModel.deleteOne({ _id: req.body._id })
  res.send({
    code: 200,
    message: '删除成功！'
  })
})
// 获取工作量列表
router.get('/workload', async (req, res) => {
  let query = req.query
  console.log(query);
  // 关联
  // let reg = RegExp(query.name, 'ig')
  // let data = []
  // let content = await personnelModel.aggregate([
  //   {
  //     $lookup: {
  //       from: 'area',
  //       localField: 'region',
  //       foreignField: '_id',
  //       as: "region",
  //     },
  //     $match: {
  //       name: reg,
  //       role: query.role
  //     }
  //   },
  //   {
  //     $lookup: {
  //       from: 'OperationWorkOrder',
  //       localField: '_id',
  //       foreignField: 'operationalPeople',
  //       as: "yy",
  //     },
  //   },
  //   {
  //     $lookup: {
  //       from: 'OperationAndMaintenanceWorkOrder',
  //       localField: '_id',
  //       foreignField: 'DevOps',
  //       as: "yw",
  //     },
  //   }
  // ])
  // 没关联
  let reg = RegExp(query.name, 'ig')
  let sel = {name:reg}
  if (query.role) {
    sel.role = query.role
  }
  let content = await personnelModel.find(sel)
  data = JSON.parse(JSON.stringify(content))
  for (let index = 0; index < data.length; index++) {
    data[index]['refuse'] = 0
    data[index]['ing'] = 0
    data[index]['end'] = 0
  }
  res.send({
    code: 200,
    message: '获取成功！',
    data
  })
})
// 获取所有点位
router.get('/areaSel', async (req, res) => {
  let data = await areaModel.find({})
  res.send({
    code: 200,
    message: '获取成功！',
    data
  })
})
module.exports = router;
